package com.gem.day12.exercise;

import java.util.*;

import com.google.common.collect.Lists;

public class PurchaseTest {
	public static void main(String[] args) {
		Purchase p1 = new Purchase("宝洁", "洗手粉", 18.5);
		Purchase p2 = new Purchase("联合利华", "肥皂", 4.5);
		Purchase p3 = new Purchase("宝洁", "牙膏", 32.5);
		Purchase p4 = new Purchase("宝洁", "毛巾", 14.5);
		Purchase p5 = new Purchase("洁利", "洗面奶", 26.0);
		Purchase p6 = new Purchase("好迪", "洗发水", 27.5);
		Purchase p7 = new Purchase("多芬", "沐浴露", 38.5);
		Purchase p8 = new Purchase("宝洁", "洗洁精", 3.4);

		//JDK9.0
		//注意:此处创建的集合是一个不可变的集合
		//List<Purchase> list = List.of(p1, p2, p3, p4, p5, p6, p7, p8);

		List<Purchase> list = Lists.newArrayList(p1, p2, p3, p4, p5, p6, p7, p8);

		//分类管理数据
		Map<String, List<Purchase>> map = processList(list);

		//统计,按照品牌价格总和降序排列
		processMap(map);

		/*Set<Entry<String, List<Purchase>>> entrySet = processMap.entrySet();
		Iterator<Entry<String, List<Purchase>>> iterator = entrySet.iterator();
		while (iterator.hasNext()) {
			Entry<String, List<Purchase>> entry = iterator.next();
			String key = entry.getKey();
			List<Purchase> value = entry.getValue();
			System.out.println(key);
			value.forEach(System.out::println);
		}*/
	}

	/**
	 * 处理List集合数据,把相同品牌的商品放在一起
	 */
	private static Map<String, List<Purchase>> processList(List<Purchase> list) {
		Map<String, List<Purchase>> map = new HashMap<>();
		//遍历List集合
		for (int i = 0; i < list.size(); i++) {
			//获取每个商品
			Purchase purchase = list.get(i);
			//判断map中是否已经存在指定的品牌
			String brand = purchase.getBrand();
			if (map.containsKey(brand)) {
				//说明该map中已经存在该品牌的商品,则直接在该品牌对应的List集合中添加该商品即可
				map.get(brand).add(purchase);
			} else {
				//说明该map中没有该品牌商品,则直接map添加元素即可
				List<Purchase> brandList = new ArrayList<>();
				brandList.add(purchase);
				map.put(brand, brandList);
			}
		}
		return map;
	}

	private static void processMap(Map<String, List<Purchase>> map) {
		//从map集合中获取所有的value
		List<List<Purchase>> values = new ArrayList<>(map.values());
		PurchasePx px = null;
		List<PurchasePx> pxList = new ArrayList<>();
		//遍历values集合,得到每个商品的对应的集合
		for (int i = 0; i < values.size(); i++) {
			//获取品牌
			String brand = values.get(i).get(0).getBrand();
			//获取该集合单价总和
			double total = values.get(i).stream().map(Purchase::getCost).reduce(Double::sum).get();
			px = new PurchasePx(brand, total);
			pxList.add(px);
		}
		Collections.sort(pxList, new Comparator<PurchasePx>() {
			@Override
			public int compare(PurchasePx o1, PurchasePx o2) {
				return o2.getTotal().compareTo(o1.getTotal());
			}
		});
		pxList.forEach(System.out::println);
	}
}
